{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, TemplateHaskell #-}
module Routes (routes) where

import Control.Monad    (msum)
import Happstack.Server
       (Browsing(EnableBrowsing), Method(GET), Response,
        ServerPart, decodeBody, defaultBodyPolicy, dir, methodM,
        serveDirectory, seeOther, toResponse)
import Pages (summaryPage,problemsServiceHandler,handleAddProblem,handleAddSubmission)
import Controllers.Login(handleLogin, handleCompleteLogin)
import qualified Paths_tuura as Cabal(version)
import Data.Version (showVersion)

-- A simple file-server. Serves a directory at a given absolute path to the same web path.
serveFS :: [String] -> ServerPart Response
serveFS dirs =
    let sitePath = foldr (.) id (map dir dirs)
        fsPath = foldr (++) "/" (map ("/"++) dirs)
    in sitePath $ serveDirectory EnableBrowsing ["index.html"] fsPath

-- | The main HTTP handler
routes :: ServerPart Response
routes =
    do decodeBody (defaultBodyPolicy "/tmp/" 4096 4096 4096)
       msum [ methodM GET >> seeOther "/tuura" (toResponse ())
            , dir "tuura" $ tuuraRoutes
            , dir "README" $ return $ toResponse "read me!"
            , let docsPath = "/home/rotsor/.cabal/share/doc/tuura-" ++ showVersion Cabal.version ++ "/html"
              in  dir "doc" $ seeOther docsPath (toResponse ())
            , serveFS ["usr","share","doc"]
            , serveFS ["home","rotsor",".cabal","share","doc"]
            , serveDirectory EnableBrowsing ["index.html"] "public"
            ]

-- | Tuura application HTTP handler
tuuraRoutes :: ServerPart Response
tuuraRoutes = do
    msum [
         summaryPage,
         dir "problemService" $ problemsServiceHandler,
         dir "addProblem" $ handleAddProblem "/tuura",
         dir "addSubmission" $ handleAddSubmission "/tuura",
         dir "login" $ handleLogin,
         dir "completeLogin" $ handleCompleteLogin
         ]
